const path = require('path');
const fs = require('fs');
const db = require("./sqlitedb.js")
const uploadserver = require("./uploadserver.js");
// const exports = require('webpack');

//获取新闻列表
exports.getnewslist = (req,res)=>{
   res.header("Access-Control-Allow-Origin","*");
   db.getinfo("SELECT * FROM NEWINFO").then((data)=>{
      var newdata = data.map((item)=>{
         var obj = {};
         obj.id = item.ID;
         obj.title = item.TITLE;
         // obj.img = "http://localhost:3000/news/images/"+ item.img;
         obj.img = item.FIRST_IMGURL;
         // obj.txt = fs.readFileSync(path.join(__dirname,"../public/news/info/"+item.txt),'utf8')
         obj.txt = item.ZHAIYAO;
         obj.click = item.CLICK;
         return obj;
     })
     res.json(newdata)
   },(err)=>{
      res.json(err);
   })
}
//获取具体的新闻信息
exports.getnewinfo = (req,res)=>{
   let id = req.params.id;
   db.getinfo(`SELECT * FROM NEWINFO WHERE ID = ${id}`).then((data)=>{
      let info = fs.readFileSync(path.join(__dirname,"../public/news/info/"+data[0].TXT_URL),'utf8')
      data[0].content = info;
      res.header("Access-Control-Allow-Origin","*");
      res.json(data);
   },(err)=>{
      res.header("Access-Control-Allow-Origin","*");
      res.json(err);
   })
}

//获取图文类别
exports.GetImgInfoType = (req,res)=>{
   db.getinfo("SELECT DISTINCT(type) FROM IMGDESCINFO").then((result)=>{
       res.header('Access-Control-Allow-Origin', '*');
       res.json(result);
   },(err)=>{
       res.header('Access-Control-Allow-Origin', '*');
       res.json(err)
   })
}
//根据类别返回
exports.GetImgListByType = (req,res)=>{
   let type = req.params.type;
   if(type == '全部'){
      db.getinfo("SELECT * FROM IMGDESCINFO").then((result) =>{
         res.header('Access-Control-Allow-Origin','*');
         res.json({status:0,result});
      },(res)=>{
         res.header('Access-Control-Allow-Origin', '*');
         res.json({status:1})
      })
   }else{
      db.getinfo(`SELECT * FROM IMGDESCINFO WHERE TYPE = '${type}'`).then((result)=>{
         res.header('Access-Control-Allow-Origin','*');
         res.json({status:0,result});
      },(res)=>{
         res.header('Access-Control-Allow-Origin', '*');
         res.json({status:1})
      })
   }
}
exports.GetImgInfoById = (req,res)=>{
   let id = req.params.id;
   db.getinfo(`SELECT * FROM IMGDESCINFO WHERE id = '${id}'`).then((result)=>{
      var txtdataurl = result[0].txt;
      var txtcontent = fs.readFileSync(path.join(__dirname,"../public/news/info/"+txtdataurl),'utf8');
      result[0].txt = txtcontent;
      res.header("Access-Control-Allow-Origin","*");
      res.json({status:0,result});
   },(err)=>{
      res.header("Access-Control-Allow-Origin","*");
      res.json({status:1})
   })
}